#include "syspushfilefilter.h"
#include <QUrlQuery>
#include "commonfunc.h"
#include <QJsonDocument>
#include <QJsonObject>
#include "logindialog.h"

CNS_SYS_REGISTER(SysPushFileFilter);

SysPushFileFilter::SysPushFileFilter()
{

}

void SysPushFileFilter::f_start(CnsComponentPtr com)
{
    f_pushFileFilter(com);
}

void SysPushFileFilter::f_pushFileFilter(CnsComponentPtr com)
{
    QUrl url("http://127.0.0.1:8080/fileFilter");
    QUrlQuery query;

    url.setQuery(query);

    CnsNetworkAccessManagerPtr network = com->property("networkAccessManager").value<CnsNetworkAccessManagerPtr>();

    QJsonObject obj;
    obj["filter"] = com->property("filter").toString();
    QJsonDocument doc(obj);
    QByteArray data = doc.toJson();

    QNetworkReply *rep = network->post(QNetworkRequest(url), data);

    LoginDialogPtr lgDialog = com->property("view").value<LoginDialogPtr>();
    lgDialog->getLoginStatus()->setText("querying...");

    // connect up the signal right away
    connect(rep, &QNetworkReply::finished,
            this, [this, rep, com]() { handlePushFileFilterData(com, rep); });
    QVariantHash v;
    v["method"] = "pushFileFilter";
    com->exec("startTimer", Q_ARG(const QVariantHash&, v));
}

void SysPushFileFilter::handlePushFileFilterData(CnsComponentPtr com, QNetworkReply *networkReply)
{
    LoginDialogPtr lgDialog = com->property("view").value<LoginDialogPtr>();
    if (!networkReply) {
        lgDialog->getLoginStatus()->setText("http query failed!");
        CNSLOG_ERROR(QString("NetworkReply is false in handlePushFileFilterData!"));
        return;
    }

    if (!networkReply->error()) {
        //convert coordinates to city name
        QJsonDocument document = QJsonDocument::fromJson(networkReply->readAll());

        QJsonObject jo = document.object();
        QVariantHash hash = jo.toVariantHash();
        if(hash["response"].toString() == "save ok!"){

            lgDialog->getLoginStatus()->setText("http query ok.");
            lgDialog->enable(true);
            com->exec("stopTimer");
        } else{
            lgDialog->getLoginStatus()->setText("http query failed!");
        }

    } else {
        lgDialog->getLoginStatus()->setText("http query failed!");
        CNSLOG_ERROR(QString("NetworkReply has error in handlePushFileFilterData!"));
    }
    networkReply->deleteLater();
}
